package com.shujia.flink.core

import org.apache.flink.runtime.state.StateBackend
import org.apache.flink.runtime.state.filesystem.FsStateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._

object Demo4CheckPoint {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    // 每 1000ms 开始一次 checkpoint
    env.enableCheckpointing(1000)

    // 高级选项：

    // 设置模式为精确一次 (这是默认值)
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃
    env.getCheckpointConfig.setCheckpointTimeout(60000)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

    //当任务取消的时候是否保留checkpoint,默认不保留
    env.getCheckpointConfig.enableExternalizedCheckpoints(ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)
    /**
      * 指定保存状态的位置
      *
      */
    //文件系统的状态后端，可以说hdfs
    val stateBackend: StateBackend = new FsStateBackend("hdfs://master:9000/data/flink/checkpoint")
    env.setStateBackend(stateBackend)


    val linesDS: DataStream[String] = env.socketTextStream("master", 8888)

    val countDS: DataStream[(String, Int)] = linesDS.flatMap(_.split(","))
      .map((_, 1))
      .keyBy(_._1)
      .sum(1) //底层是聚合状态

    countDS.print()

    env.execute()

    /**
      * 任务失败之后重新启动任务需要指定从那一个checkpoint的位置恢复任务
      * hdfs://master:9000/data/flink/checkpoint/a33b5d76bc0178cd0124e23c810a7fca/chk-44
      *
      *
      * 命令行恢复
      * flink run -c com.shujia.flink.core.Demo4CheckPoint -s hdfs://master:9000/data/flink/checkpoint/8d1f296dd3d
      * ab8957d114453b34bb434/chk-201 flink-1.0.jar
      *
      */
  }

}
